<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({})
  }
})

const chartRef = ref(null)
let chart = null

// 模拟数据
const mockData = {
  temperature: Array.from({ length: 24 }, () => Math.random() * 10 + 20),
  humidity: Array.from({ length: 24 }, () => Math.random() * 20 + 50),
  gas: Array.from({ length: 24 }, () => Math.random() * 5),
  noise: Array.from({ length: 24 }, () => Math.random() * 30 + 40)
}

const initChart = () => {
  if (!chartRef.value) return

  chart = echarts.init(chartRef.value)
  
  const option = {
    title: {
      text: '环境数据监控'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['温度', '湿度', '可燃气体', '噪音']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({ length: 24 }, (_, i) => `${i}:00`)
    },
    yAxis: [
      {
        type: 'value',
        name: '温度/湿度',
        position: 'left'
      },
      {
        type: 'value',
        name: '气体/噪音',
        position: 'right'
      }
    ],
    series: [
      {
        name: '温度',
        type: 'line',
        data: mockData.temperature,
        smooth: true,
        itemStyle: {
          color: '#F56C6C'
        }
      },
      {
        name: '湿度',
        type: 'line',
        data: mockData.humidity,
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '可燃气体',
        type: 'line',
        yAxisIndex: 1,
        data: mockData.gas,
        smooth: true,
        itemStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '噪音',
        type: 'line',
        yAxisIndex: 1,
        data: mockData.noise,
        smooth: true,
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }

  chart.setOption(option)
}

// 监听窗口大小变化
const handleResize = () => {
  chart && chart.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  chart && chart.dispose()
})

// 更新图表数据
const updateChart = (newData) => {
  if (!chart) return
  
  chart.setOption({
    series: [
      { data: newData.temperature },
      { data: newData.humidity },
      { data: newData.gas },
      { data: newData.noise }
    ]
  })
}

// 暴露更新方法
defineExpose({
  updateChart
})
</script>

<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>